package com.cirkana.viewer.data;

import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.cirkana.CirkanaException;
import com.cirkana.data.DataException;

public class SQLiteOpenHelperCirkanaImpl extends SQLiteOpenHelper {

	private LocalDataConfig config;
	private CirkanaException lastException;

	protected boolean hasException() {
		return this.lastException != null;
	}

	protected CirkanaException getLastException() {
		try {
			return this.lastException;
		} finally {
			this.lastException = null;
		}
	}

	protected SQLiteOpenHelperCirkanaImpl(Context context, LocalDataConfig config) {
		super(context, config.getLocalDataBaseName(), null, config.getLocalDataBaseVersion());
		this.config = config;
		if (config.mustDeleteDataBaseBefore())
			context.deleteDatabase(this.config.getLocalDataBaseName());
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {
			createDatabase(db);
		} catch (CirkanaException e) {
			this.lastException = e;
		}
	}

	private void createDatabase(SQLiteDatabase db) throws DataException {
		executeSentences(db, config.getCreateSentences());
		executeSentences(db, config.getInitialSentences());
	}

	private void executeSentences(SQLiteDatabase db, List<String> sentences) throws DataException {
		try {
		for (String sql : sentences)
			db.execSQL(sql);
		} catch (Exception e) {
			throw new DataException(e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
	}

}
